import wtforms
from wtforms.validators import Length, EqualTo
from applications.models.frontend import User


# 用于后端进行表单验证
class Login(wtforms.Form):
    username = wtforms.StringField(validators=[Length(min=2, max=20, message='用户名长度为2-20位')])
    password = wtforms.StringField(validators=[Length(min=2, max=20, message='密码长度最少为8位')])

    def validate_username(self, field):
        user = User.query.filter_by(username=field.data).first()
        phone = User.query.filter_by(phone=field.data).first()
        if not user and not phone:
            raise wtforms.ValidationError('用户不存在！')  # 数据如果不存在抛出异常


class Register(wtforms.Form):
    username = wtforms.StringField(validators=[Length(min=2, max=20, message='用户名长度为2-20位')])
    phone = wtforms.StringField(validators=[Length(min=11,max=11, message='手机号长度为11位')])
    password = wtforms.StringField(validators=[Length(min=8, message='密码长度最少为8位')])
    confirm_password = wtforms.StringField(validators=[EqualTo('password')])

    # 自定义验证
    def validate_username(self, field):
        username = field.data
        user = User.query.filter_by(username=username).first()
        if user:
            raise wtforms.ValidationError('用户名已存在')  # 数据如果存在抛出异常

    def validate_phone(self, field):
        phone = User.query.filter_by(phone=field.data).first()
        if phone:
            raise wtforms.ValidationError('手机号已存在')  # 数据如果存在抛出异常
